package main

import (
	"fmt"
	"strconv"

	// "go-data-washing/washingMachine"

	"go-data-washing/valid"
	"go-data-washing/webData"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type DbSetting struct {
	Type     string
	UserName string
	Password string
	Dbname   string
}

func connectDB(setting DbSetting) *gorm.DB {
	options := fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", setting.UserName, setting.Password, setting.Dbname)

	db, err := gorm.Open(setting.Type, options)

	if err != nil {
		panic(err)
	}

	return db
}

func EmptyFormat(d string) (string, bool) {
	return d, true
}

func Run() {
	setting := DbSetting{"mysql", "root", "123456", "blog_service"}
	db := connectDB(setting)
	defer db.Close()
	webSource := webData.WebRead{0, 10, -1, 200, 0}
	webClean := webData.WebCleanWrite{}
	// webDirty := webData.WebDirtyWrite{}

	maybeList := []valid.Middle{
		valid.Leve1Middle,
		// valid.Leve2Middle,
	}

	for {

		rows, err := webSource.Read(db)
		_rowsClean := []map[string]string{}
		_rowsDirty := []map[string]string{}

		if err != nil {
			fmt.Println(err)
			return
		}

		for _, row := range rows {

			_row := row
			isDirty := false

			for _, middle := range maybeList {

				_row, isDirty = middle.CheckAndFormat(_row)

				if !isDirty {
					break
				}

			}

			_row["clean_count"] = strconv.Itoa(webSource.CleanCount + 1)

			if isDirty {
				_rowsDirty = append(_rowsDirty, _row)
			} else {
				_rowsClean = append(_rowsClean, _row)
			}

		}

		fmt.Println(len(_rowsClean), len(_rowsDirty))

		if len(_rowsClean) > 0 {
			webClean.Write(db, _rowsClean)
		}

		webSource.Update(db, _rowsClean)
		webSource.Update(db, _rowsDirty)

	}

}

func main() {

	Run()

}
